import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  getNewsPhotos,
  searchNewsPhotos,
  getNewsPhotoDetail,
  createNewsPhoto,
  updateNewsPhoto,
  deleteNewsPhoto
} from '@/api/newsPhotos'

export const usePhotoStore = defineStore('photo', () => {
  const photoList = ref([])
  const currentPhoto = ref(null)
  const loading = ref(false)
  const pagination = ref({
    page: 1,
    pageSize: 10,
    total: 0
  })

  const fetchPhotos = async (params = {}) => {
    loading.value = true
    try {
      const res = await getNewsPhotos({
        ...params,
        page: pagination.value.page,
        pageSize: pagination.value.pageSize
      })
      photoList.value = res.data.list
      pagination.value.total = res.data.total
    } finally {
      loading.value = false
    }
  }

  const searchPhotos = async (params) => {
    loading.value = true
    try {
      const res = await searchNewsPhotos(params)
      photoList.value = res.data.list
      pagination.value.total = res.data.total
    } finally {
      loading.value = false
    }
  }

  const fetchPhotoDetail = async (id) => {
    loading.value = true
    try {
      const res = await getNewsPhotoDetail(id)
      currentPhoto.value = res.data
    } finally {
      loading.value = false
    }
  }

  const addPhoto = async (data) => {
    await createNewsPhoto(data)
    await fetchPhotos()
  }

  const editPhoto = async (id, data) => {
    await updateNewsPhoto(id, data)
    await fetchPhotos()
  }

  const removePhoto = async (id) => {
    await deleteNewsPhoto(id)
    await fetchPhotos()
  }

  return {
    photoList,
    currentPhoto,
    loading,
    pagination,
    fetchPhotos,
    searchPhotos,
    fetchPhotoDetail,
    addPhoto,
    editPhoto,
    removePhoto
  }
})